package com.recruit.server.config;

import com.recruit.server.common.Constant;
import com.recruit.server.common.HeaderInfo;
import com.recruit.server.common.HeaderLocal;
import com.recruit.server.common.utils.CookieUtil;
import com.recruit.server.common.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@Component
public class ArgumentResolver implements HandlerMethodArgumentResolver {

    @Value("${spring.profiles.active}")
    private String active;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == HeaderInfo.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        HeaderInfo headerInfo = (HeaderInfo) request.getSession().getAttribute(Constant.CURRENT_USER);
        // String header = CookieUtil.readLoginToken(request);
        // log.info("header:{}", header);
        // if (!StringUtils.isEmpty(header)) {
        //     headerInfo = JSON.toJavaObject(JSON.parseObject(ToolUtil.decode(header)), HeaderInfo.class);
        // }
        log.info("resolveArgument headerInfo = {}", JSON.toJSONString(headerInfo));
        HeaderLocal.setHeaderInfo(headerInfo);
        return headerInfo;
    }
}